package com.demo.attC;

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class StreamForker<T> {

    private final Stream<T> stream;
    private final Map<Object, Function<Stream<T>, ?>> forks = new HashMap<>();

    public StreamForker(Stream<T> stream) {
        this.stream = stream;
    }

    public StreamForker<T> fork(Object key, Function<Stream<T>, ?> f) {
    	//使用一个键对流上的函数进行索引
        forks.put(key, f);
        //返回this从而保证多次流畅的调用fork方法
        return this;
    }

    //所有在fork方法添加的操作的执行都是通过getResults方法的调用触发
    public Results getResults() {
        ForkingStreamConsumer<T> consumer = ForkingStreamConsumer.build(forks);
        try {
            stream.sequential().forEach(consumer);
        } finally {
            consumer.finish();
        }
        return consumer;
    }

}
